package com.shenganyuan.smac.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.oklib.utils.Logger.Logger;
import com.oklib.utils.view.ToastUtils;
import com.oklib.widget.BottomNavigationViewEx;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.beans.LocationInfo;
import com.shenganyuan.smac.common.data.AnyPrefUtil;
import com.shenganyuan.smac.contact.FrgContact;
import com.shenganyuan.smac.me.FrgMainMe;
import com.shenganyuan.smac.msg.FrgMainMsg;
import com.shenganyuan.smac.work.FrgMainWork;

import butterknife.BindView;
import me.yokeyword.fragmentation.SupportFragment;

import static com.shenganyuan.smac.common.Config.POSITION_AUTO_SERVICE;

/**
 * @author Damon.Han
 */
public class MainActivity extends BaseActivity {
    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    public static final int FOURTH = 3;

    @BindView(R.id.main_frame_content)
    FrameLayout frameContent;
    @BindView(R.id.navi_bottom_main)
    BottomNavigationViewEx naviMain;
    @BindView(R.id.container)
    RelativeLayout container;
    private SupportFragment[] mFragments = new SupportFragment[4];
    private int prePosition = 0;
    //
    public static final String RECEIVER_ACTION = "location_in_background";

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {
        naviMain.enableAnimation(false);
        naviMain.enableShiftingMode(false);
        naviMain.enableItemShiftingMode(false);
        SupportFragment firstFragment = findFragment(FrgMainWork.class);
        if (firstFragment == null) {
            mFragments[FIRST] = FrgMainWork.newInstance();
            mFragments[SECOND] = FrgMainMsg.newInstance();
            mFragments[THIRD] = FrgContact.newInstance();
            mFragments[FOURTH] = FrgMainMe.newInstance();

            loadMultipleRootFragment(R.id.main_frame_content, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND],
                    mFragments[THIRD],
                    mFragments[FOURTH]);
        } else {
            mFragments[FIRST] = firstFragment;
            mFragments[SECOND] = findFragment(FrgMainMsg.class);
            mFragments[THIRD] = findFragment(FrgContact.class);
            mFragments[FOURTH] = findFragment(FrgMainMe.class);
        }
        naviMain.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                prePosition = naviMain.getCurrentItem();
                int position = naviMain.getMenuItemPosition(item);
                //消息页面刷新
                if (mFragments[position] instanceof FrgMainMsg) {
                    FrgMainMsg frgMainMsg = (FrgMainMsg) mFragments[position];
                    frgMainMsg.refreshPage();
                } else if (mFragments[position] instanceof FrgMainWork) {
                    FrgMainWork frgMainMsg = (FrgMainWork) mFragments[position];
                    frgMainMsg.refreshPage();
                }
                showHideFragment(mFragments[position], mFragments[prePosition]);
                return true;
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RECEIVER_ACTION);
        registerReceiver(locationChangeBroadcastReceiver, intentFilter);
        //页面启动5秒后开启服务
        if (POSITION_AUTO_SERVICE) {
            container.postDelayed(new Runnable() {
                @Override
                public void run() {
                    App.getInstance().startLocationService();
                }
            }, 5000);
        }
    }

    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;

    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
                ActivityCompat.finishAfterTransition(this);
            } else {
                TOUCH_TIME = System.currentTimeMillis();
                ToastUtils.showToast(mContext, "再按一次退出" + getResources().getString(R.string.app_name));
            }

        }
    }


    /**
     * 打印定位信息
     */
    private BroadcastReceiver locationChangeBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(RECEIVER_ACTION)) {
                String locationResult = intent.getStringExtra("result");
                if (null != locationResult && !locationResult.trim().equals("")) {
                    //自动定位结果处理
                    Logger.e(locationResult);
                    //保存处理结果
                }
                LocationInfo locationInfo = (LocationInfo) intent.getSerializableExtra("locationInfo");
                if (locationInfo != null) {
                    AnyPrefUtil.saveLocationInfo(locationInfo);
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        App.getInstance().stopLocationService();
        if (locationChangeBroadcastReceiver != null) {
            unregisterReceiver(locationChangeBroadcastReceiver);
        }
        super.onDestroy();
    }

}
